package com.itcaius.weblog.admin.event.subscriber;

import com.itcaius.weblog.admin.event.DeleteArticleEvent;
import com.itcaius.weblog.admin.service.AdminStatisticsService;
import com.itcaius.weblog.search.LuceneHelper;
import com.itcaius.weblog.search.index.ArticleIndex;
import lombok.extern.slf4j.Slf4j;
import org.apache.lucene.index.Term;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

/**
 * @author Caius
 * @description
 * @since Created in 2025-06-12
 */
@Component
@Slf4j
public class DeleteArticleSubscriber implements ApplicationListener<DeleteArticleEvent> {

    @Autowired
    private LuceneHelper luceneHelper;
    @Autowired
    private AdminStatisticsService adminStatisticsService;

    @Override
    public void onApplicationEvent(DeleteArticleEvent event) {
        Long articleId = event.getArticleId();

        String threadName = Thread.currentThread().getName();

        log.info("==> threadName: {}", threadName);
        log.info("==> 文章删除事件消费成功，articleId: {}", articleId);

        Term condition = new Term(ArticleIndex.COLUMN_ID, String.valueOf(articleId));

        long count = luceneHelper.deleteDocument(ArticleIndex.NAME, condition);

        log.info("==> 删除文章对应 Lucene 文档结束，articleId: {}，受影响行数: {}", articleId, count);

        adminStatisticsService.statisticsCategoryArticleTotal();
        log.info("==> 统计分类下的文章数量结束...");

        adminStatisticsService.statisticsTagArticleTotal();
        log.info("==> 统计标签下的文章数量结束...");
    }
}
